package com.printeverywhere.servlet;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.dto.ItemAuctionImage;
import com.printeverywhere.util.SearchCriteria;

public class DownloadFileServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doDownload(request, response, getServletContext().getRealPath(request.getParameter("filename")), "sample");
	}

	/**
     *  Sends a file to the ServletResponse output stream.  Typically
     *  you want the browser to receive a different name than the
     *  name the file has been saved in your local database, since
     *  your local names need to be unique.
     *
     *  @param req The request
     *  @param resp The response
     *  @param filename The name of the file you want to download.
     *  @param original_filename The name the browser should receive.
     */
    private void doDownload( HttpServletRequest req, HttpServletResponse resp,
                             String filename, String original_filename )
        throws IOException
    {
        File                f        = new File(filename);
        int                 length   = 0;
        ServletOutputStream op       = resp.getOutputStream();
        ServletContext      context  = getServletConfig().getServletContext();
        String              mimetype = context.getMimeType( filename );

        SearchCriteria searchCriteria = new SearchCriteria();
		searchCriteria.setAttribute("id.imagePath", req.getParameter("filename"));
		List<ItemAuctionImage> itemAuctionImageList = (List<ItemAuctionImage>) CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, ItemAuctionImage.class);

		String extention = ".jpeg";
		if(itemAuctionImageList != null && itemAuctionImageList.size() > 0) {
			ItemAuctionImage itemAuctionImage = itemAuctionImageList.get(0);
			if(itemAuctionImage.getId().getContentType().equals("application/msword"))
				extention = ".doc";
			else if(itemAuctionImage.getId().getContentType().equals("text/plain"))
				extention = ".txt";
			else if(itemAuctionImage.getId().getContentType().equals("application/pdf"))
				extention = ".pdf";
			else if(itemAuctionImage.getId().getContentType().equals("audio/x-wav"))
				extention = ".wav";
			else if(itemAuctionImage.getId().getContentType().equals("audio/midi"))
				extention = ".mid";
			else if(itemAuctionImage.getId().getContentType().equals("video/quicktime"))
				extention = ".mov";
			else if(itemAuctionImage.getId().getContentType().equals("video/msvideo"))
				extention = ".avi";
		}
        //
        //  Set the response and go!
        //
        //
        resp.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
        resp.setContentLength( (int)f.length() );
        resp.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + extention + "\"" );

        //
        //  Stream to the requester.
        //
        byte[] bbuf = new byte[1024];
        DataInputStream in = new DataInputStream(new FileInputStream(f));

        while ((in != null) && ((length = in.read(bbuf)) != -1))
        {
            op.write(bbuf,0,length);
        }

        in.close();
        op.flush();
        op.close();
    }
}
